<template>
  <nav-bar title="运单详情"></nav-bar>
  <div
    v-bind:class="[
      'waybill-detail-box',
      orderStaus === 19 || orderStaus === BillTabsEm.FINISHED.value || orderStaus === BillTabsEm.CANCELLED.value
        ? 'modify-bottom'
        : ''
    ]"
  >
    <!-- 步骤条 运输状态 -->
    <order-step :orderStep="orderStaus" :consComments="detailList.consComments" :detail="detailList"></order-step>

    <!-- 订单信息 -->
    <div class="order-address list-init">
      <div span="24" class="address-name">
        {{ Number(DataTypeEm.ORDER.value) === Number(detailList.dataType) ? '订单' : '运单' }}信息
      </div>
      <div class="detail-init">
        <van-row justify="space-between">
          <van-col>
            {{ Number(DataTypeEm.ORDER.value) === Number(detailList.dataType) ? '订单号' : '运单号' }}
          </van-col>
          <van-col>
            <span>
              {{
                Number(DataTypeEm.ORDER.value) === Number(detailList.dataType) ? detailList.orderNo : detailList.billNo
              }}
            </span>
            <span
              class="copy"
              :data-clipboard-text="orderStaus === 12 || orderStaus === 19 ? detailList.orderNo : detailList.billNo"
              @click="handleCopy"
            >
              复制
            </span>
          </van-col>
        </van-row>
        <van-row justify="space-between">
          <van-col>
            {{ orderStaus === BillTabsEm.WAIT_RE.value || orderStaus === 19 ? '创建时间' : '更新时间' }}
          </van-col>
          <van-col>
            <span>
              {{
                orderStaus === BillTabsEm.WAIT_RE.value || orderStaus === 19
                  ? detailList.createTime
                  : detailList.updateTime
              }}
            </span>
          </van-col>
        </van-row>
      </div>
    </div>

    <!-- 地址 -->
    <div class="order-address list-init">
      <div span="24" class="address-name">
        <div class="address-layout">
          {{ detailList.sendCityName }}{{ detailList.sendCountyName }}
          <span class="line"></span>
          {{ detailList.receiveCityName }}{{ detailList.receiveCountyName }}
        </div>
      </div>
      <div class="detail-init">
        <van-row>
          <van-col span="16">
            <!-- 预估距离约{{ detailList.distance ? (detailList.distance / 1000).toFixed(1) : 0 }}km -->
            运单监控
          </van-col>
          <van-col
            v-show="
              orderStaus > BillTabsEm.FORWARDING.value &&
              detailList.loadReceiptStatus === LoadReceiptStatusEm.ALREADY_UPLOAD.value
            "
            span="8"
            class="look-map"
            @click="handleEnterMap"
          >
            查看轨迹
          </van-col>
        </van-row>
      </div>
    </div>

    <!-- 车货信息 -->
    <goods-msg v-if="orderStaus !== BillTabsEm.FINISHED.value" :detailList="detailList"></goods-msg>

    <!-- 装卸信息 -->
    <div class="add-goods list-init" v-if="orderStaus !== BillTabsEm.FINISHED.value">
      <div class="address-name">装卸信息</div>
      <div class="detail-init">
        <van-row>
          <van-col span="5">装货时间</van-col>
          <van-col span="19">{{ detailList.shipTime }}</van-col>
        </van-row>
        <van-row>
          <van-col span="5">装货地点</van-col>
          <van-col span="19">
            {{ detailList.sendProvinceName }}{{ detailList.sendCityName }}{{ detailList.sendCountyName
            }}{{ detailList.sendDetailAddress }}
          </van-col>
        </van-row>
        <van-row>
          <van-col span="5">卸货时间</van-col>
          <van-col span="19">{{ detailList.unloadTime }}</van-col>
        </van-row>
        <van-row>
          <van-col span="5">卸货地点</van-col>
          <van-col span="19">
            {{ detailList.receiveProvinceName }}{{ detailList.receiveCityName }}{{ detailList.receiveCountyName
            }}{{ detailList.receiveDetailAddress }}
          </van-col>
        </van-row>
      </div>
    </div>

    <!-- 运费信息 -->
    <!-- <div class="list-init">
      <div class="address-name">运费信息</div>
      <div class="detail-init">
        <van-row>
          <van-col span="8">货主出价</van-col>
          <van-col span="16">
            {{
              detailList.settleType === SettleTypeEm.Trip.value
                ? detailList.price + '元/趟'
                : (detailList.price || '-') + '元/吨'
            }}
          </van-col>
        </van-row>
        <van-row>
          <van-col span="8">合计</van-col>
          <van-col span="16">{{ detailList.totalPrice || 0 }}元</van-col>
        </van-row>
      </div>
    </div> -->

    <!-- 运费信息 -->
    <DetailInfo :list="freightList" :title="'运费信息'" />

    <!-- 货主信息 -->
    <goods-owner :consId="detailList.consId" :driverMsg="driverMsg"></goods-owner>

    <!-- 操作按钮 -->

    <van-row
      gutter="20"
      class="handle-button"
      justify="center"
      v-if="orderStaus !== 19 && orderStaus !== BillTabsEm.CANCELLED.value && detailList.consToDriverStatus !== 2"
    >
      <!--待接单-->
      <template v-if="orderStaus === BillTabsEm.WAIT_RE.value">
        <van-col span="12">
          <van-button type="primary" class="connect" @click="handleCancelOrser(detailList.id)">
            <svg-icon name="cancel-order"></svg-icon>
            &nbsp;取消订单
          </van-button>
        </van-col>
        <!-- <van-col span="12" v-if="detailList.pointType === PointTypeEm.FIND.value">
          <van-button type="primary" class="upload-bill" @click="handleAssign(detailList.id)">
            <svg-icon name="assigned-driver"></svg-icon>
            &nbsp;指派{{ detailList.driverMobile ? '司机' : '承运商' }}
          </van-button>
        </van-col> -->
        <!-- <van-col span="12" v-else> -->
        <van-col span="12" v-if="detailList.pointType === PointTypeEm.SEND.value">
          <van-button type="primary" class="upload-bill" @click="goTelphone">
            <svg-icon name="tel"></svg-icon>
            &nbsp;联系{{ detailList.driverMobile ? '司机' : '承运商' }}
          </van-button>
        </van-col>
      </template>

      <!--待装货状态-->
      <template v-else-if="orderStaus === BillTabsEm.FORWARDING.value">
        <van-col span="12">
          <van-button type="default" class="connect" @click="goTelphone">
            <svg-icon name="tel"></svg-icon>
            &nbsp;联系{{ detailList.driverMobile ? '司机' : '承运商' }}
          </van-button>
        </van-col>
        <van-col span="12" v-if="detailList.loadReceiptStatus === LoadReceiptStatusEm.ALREADY_UPLOAD.value">
          <van-button
            type="primary"
            class="upload-bill"
            @click="onCheckBill(detailList, BillOpeartionEm.BILL.value, String(BillOpearStatusEm.SHIPMENT.value))"
          >
            <svg-icon name="receipt"></svg-icon>
            &nbsp; 查看单据
          </van-button>
        </van-col>
      </template>

      <!--运输中-->
      <template v-else-if="orderStaus === BillTabsEm.In_TRANSIT.value">
        <van-col span="12">
          <van-button type="default" class="connect" @click="goTelphone">
            <svg-icon name="tel"></svg-icon>
            &nbsp;联系{{ detailList.driverMobile ? '司机' : '承运商' }}
          </van-button>
        </van-col>
        <van-col span="12">
          <van-button
            type="primary"
            class="connect"
            @click="onCheckBill(detailList, BillOpeartionEm.BILL.value, String(BillOpearStatusEm.SHIPMENT.value), 0, 0)"
          >
            <svg-icon name="receipt"></svg-icon>
            &nbsp; 查看单据
          </van-button>
        </van-col>
      </template>

      <!--待签收-->
      <template v-else-if="orderStaus === BillTabsEm.TO_SIGNED.value">
        <van-col span="12">
          <van-button type="primary" size="small" class="sure" @click="goTelphone()">联系司机</van-button>
        </van-col>
        <van-col span="12">
          <van-button
            type="primary"
            class="upload-bill"
            v-if="detailList.unloadReceiptStatus === UnloadReceiptStatusEm.ALREADY_UPLOAD.value"
            @click="onCheckBill(detailList, BillOpeartionEm.SIGN.value, String(BillOpearStatusEm.UNLOADING.value))"
          >
            <svg-icon name="receipt"></svg-icon>
            &nbsp; 查看单据
          </van-button>
        </van-col>
      </template>

      <!--已签收-->
      <template v-else-if="orderStaus === BillTabsEm.SIGNED.value">
        <van-col span="12">
          <van-button
            type="primary"
            class="connect"
            @click="onCheckBill(detailList, BillOpeartionEm.SIGN.value, String(BillOpearStatusEm.SHIPMENT.value), 1, 0)"
          >
            <svg-icon name="receipt"></svg-icon>
            &nbsp; 查看单据
          </van-button>
        </van-col>

        <van-col span="12" v-if="detailList.payStatus === PayStatusEm.NO_RECEIPT_PAY.value">
          <van-button type="primary" class="connect" @click="onShowPwd">
            <svg-icon name="receipt"></svg-icon>
            &nbsp; 回单支付
          </van-button>
        </van-col>

        <van-col span="12" v-else-if="detailList.payStatus === PayStatusEm.NO_MONTH_PAY.value">
          <van-button type="primary" @click="onShowPwd">
            <svg-icon name="receipt"></svg-icon>
            &nbsp; 月结支付
          </van-button>
        </van-col>
      </template>

      <!--已完成待评价状态-->
      <template v-else-if="detailList.consToDriverStatus === 1">
        <van-col span="12">
          <van-button type="primary" @click="onGoEvaluate(detailList)">评价司机</van-button>
        </van-col>
        <van-col span="12">
          <van-button
            type="primary"
            class="connect"
            @click="onCheckBill(detailList, BillOpeartionEm.SIGN.value, String(BillOpearStatusEm.SHIPMENT.value), 1, 0)"
          >
            <svg-icon name="receipt"></svg-icon>
            &nbsp; 查看单据
          </van-button>
        </van-col>
      </template>
    </van-row>
  </div>
  <PhonePopup :isShow="isTelPhoneShow" :telNumber="contactTel" @cancel_show="isTelPhoneShow = false" />
  <van-popup v-model:show="passwordPoppup" position="bottom">
    <div class="passwordPoppup">
      <div class="memo">请输入支付密码</div>
      <van-password-input :value="payPassword" :focused="true" />
      <van-number-keyboard
        v-model="payPassword"
        :show="true"
        @input="onCommit"
        maxlength="6"
        @blur="passwordPoppup = false"
      />
    </div>
  </van-popup>
  <div v-loading="{ isLoading: loadingList.isLoading, isBottomMask: loadingList.isBottomMask }"></div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs, onMounted, computed } from 'vue'
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
import { Toast, Dialog } from 'vant'
import Clipboard from 'clipboard'
import NavBar from '@/components/NavBar.vue'
import OrderStep from './components/OrderStep.vue'
import GoodsMsg from './components/GoodsMsg.vue'
import GoodsOwner from './components/GoodsOwner.vue'
import PhonePopup from '@/components/PhonePopup.vue'
import DetailInfo from './components/DetailInfo.vue'
import { api } from '@/http/api'
import http from '@/http'
import store from '@/store/index'
import storage from 'good-storage'
import { WAY_BILL_MAP_KEY } from '@/utils/constant'
import { BillTabsEm } from '@/store/enums'
import {
  LoadReceiptStatusEm,
  UnloadReceiptStatusEm,
  LoadRejectStatusEm,
  UnloadRejectStatusEm,
  BillOpearStatusEm,
  PointTypeEm,
  PayStatusEm,
  BillOpeartionEm,
  DataTypeEm,
  SettleTypeEm
} from './utils/enums'
interface LoadingList {
  isLoading: boolean
  isBottomMask: boolean
}

interface State {
  orderId: string
  orderStaus: number
  detailList: any
  isShowLoading: boolean
  driverMsg: any
  passwordPoppup: boolean
  payPassword: string
  contactTel: string
  loadingList: LoadingList
}

export default defineComponent({
  name: 'WaybillDetail',
  components: {
    NavBar,
    OrderStep,
    GoodsMsg,
    GoodsOwner,
    PhonePopup,
    DetailInfo
  },
  setup() {
    const loadingList = {
      isLoading: false,
      isBottomMask: false
    }

    const state = reactive<State>({
      orderId: '',
      orderStaus: -1,
      detailList: {},
      isShowLoading: false,
      driverMsg: {},
      passwordPoppup: false, //展示密码框
      payPassword: '', //密码
      contactTel: '',
      loadingList: { ...loadingList }
    })
    const router = useRouter(),
      route = useRoute()
    // 获取路由参数
    const { id, dataType } = route.query as {
      dataType: string // 单据类型
      [propname: string]: any
    }
    state.orderId = id
    const isTelPhoneShow = ref(false)

    const freightList = ref<{ title: string; value: string; valueStyle?: any }[]>([]) // 运费信息

    onMounted(() => {
      initWaybillDetail()
    })

    // 构建运费信息
    const buildFreightData = (data: any): void => {
      let trap = data.settleType === SettleTypeEm.Trip.value ? data.price + '元/趟' : data.price + '元/吨'
      const list = [
        {
          title: '货主出价',
          value: trap
        },
        {
          title: '运费合计',
          value: (data.totalPrice || '-') + '元',
          valueStyle: {
            color: '#101736',
            fontWeight: 600
          }
        }
      ]
      if (data.prepaymentRatio) {
        list.push({
          title: '预付',
          value: `${data.prepaymentRatio}%`
        })
      }
      if (data.payRatio) {
        list.push({
          title: '到付',
          value: `${data.payRatio}%`
        })
      }
      if (data.receiptRatio) {
        list.push({
          title: '回单付',
          value: `${data.receiptRatio}%`
        })
      }
      if (data.settleRatio) {
        list.push({
          title: '月结',
          value: `${data.settleRatio}%`
        })
      }
      if (data.settleDate) {
        list.push({
          title: '月结日期',
          value: data.settleDate || ''
        })
      }

      freightList.value = list
    }

    // 获取运单数据
    const initWaybillDetail = async () => {
      let url = ''
      if (Number(dataType) === Number(DataTypeEm.ORDER.value)) {
        url = api.getOrderDeatil
      } else {
        url = api.getWaybillDetail
      }
      state.loadingList = { ...state.loadingList, isLoading: true, isBottomMask: true }

      await http<string>({
        url,
        method: 'post',
        data: { id }
      })
        .then((res: any) => {
          const billOrderStatus = Number(dataType) === Number(DataTypeEm.ORDER.value) ? res.orderStatus : res.status
          state.orderStaus = billOrderStatus
          state.detailList = Object.assign(res, { billOrderStatus }, { dataType: Number(dataType) })
          state.driverMsg = {
            carrierName: res.carrierName,
            carrierMobile: res.carrierMobile,
            driverName: res.driverName,
            driverMobile: res.driverMobile,
            plateNo: res.plateNo,
            status: res.status,
            carrierId: res.carrierId,
            driverId: res.driverId
          }
          state.loadingList = { ...loadingList }
          buildFreightData(state.detailList)
        })
        .catch(err => {
          state.loadingList = { ...loadingList }
        })
    }
    // 查看单据
    const onCheckBill = (
      item: any,
      billStatusType: number,
      type: '1' | '2' | string,
      showTab = 0,
      showOpeartion = 1
    ): void => {
      router.push({
        name: 'Receipt',
        query: {
          billId: item.id,
          billStatusType,
          showTab,
          type,
          showOpeartion,
          payStatus: item.payStatus
        }
      })
    }

    //联系司机
    const goTelphone = () => {
      state.contactTel = state.detailList.driverMobile ? state.detailList.driverMobile : state.detailList.carrierMobile
      isTelPhoneShow.value = true
    }

    // 查看地图
    const handleEnterMap = () => {
      storage.session.set(WAY_BILL_MAP_KEY, state.detailList)
      router.push({
        path: '/waybill/transport-map'
        // query: { orderStaus: state.orderStaus, sendLatitude, sendLongitude, receiveLatitude, receiveLongitude }
      })
    }

    // 点击复制运单号
    const handleCopy = () => {
      let clipboard = new Clipboard('.copy')
      clipboard.on('success', e => {
        Toast('复制成功')
        //  释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        Toast('当前手机不支持自动复制')
        // 释放内存
        clipboard.destroy()
      })
    }

    // 取消订单
    const handleCancelOrser = (id: string) => {
      Dialog.confirm({
        title: '',
        message: '您确认取消当前订单吗'
      })
        .then(() => {
          sureRequest()
        })
        .catch(() => {
          //
        })

      function sureRequest() {
        http<string>({
          url: api.updateCancelOrder,
          method: 'post',
          data: { id }
        }).then((res: any) => {
          store.commit('waybill/updateRefresh', true)
          router.go(-1)
        })
      }
    }

    // 指派司机
    const handleAssign = (id: string) => {
      router.push({
        name: 'AssignOrder',
        params: { id }
      })
    }

    // 支付
    const onCommit = async (value: any): Promise<void> => {
      if (String(state.payPassword).length < 5) return
      const updateData: any = {
        billId: id, //	运单id		true
        password: state.payPassword + value //	支付密码
      }

      if (state.detailList.payStatus === PayStatusEm.NO_RECEIPT_PAY.value) {
        // 回单付
        updateData.amount = state.detailList.receiptAmount || 0
        updateData.type = BillOpeartionEm.CALLBACK.value
      } else if (state.detailList.payStatus === PayStatusEm.NO_MONTH_PAY.value) {
        updateData.amount = state.detailList.settleAmount || 0
        updateData.type = BillOpeartionEm.MOUNTH.value
      }
      const result = await store.dispatch('waybill/handleTransportBillConfirmCons', updateData)
      if (result) {
        Toast.success('操作成功')
        setTimeout(() => {
          router.go(-1)
        }, 2000)
      }
    }

    // 显示支付密码弹窗
    const onShowPwd = (): void => {
      state.payPassword = ''
      state.passwordPoppup = true
    }

    //去评价
    const onGoEvaluate = () => {
      router.push({ name: 'Evaluate', params: { params: JSON.stringify(state.detailList) } })
    }

    return {
      ...toRefs(state),
      isTelPhoneShow,
      goTelphone,
      handleEnterMap,
      handleCopy,
      handleCancelOrser,
      handleAssign,
      BillTabsEm,
      LoadReceiptStatusEm,
      UnloadReceiptStatusEm,
      LoadRejectStatusEm,
      UnloadRejectStatusEm,
      BillOpearStatusEm,
      PointTypeEm,
      PayStatusEm,
      BillOpeartionEm,
      SettleTypeEm,
      DataTypeEm,
      onCheckBill,
      onShowPwd,
      onCommit,
      onGoEvaluate,
      freightList
    }
  }
})
</script>

<style lang="scss" scoped src="./css/waybillDetail.scss"></style>
